package com.java.main.pdf;

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.font.FontProvider;
import com.itextpdf.styledxmlparser.jsoup.helper.StringUtil;

import java.io.*;
import java.lang.reflect.Field;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class html {

    public static void main(String[] args) throws Exception{
        Pdf("./java/src/main/resources/subcontractTemplate.html",data());
    }

    private static Template data(){
        Template text = new Template();
        text.setCode("2011221231311");
        text.setPartyA("甲方企业");
        text.setLegalPersonA("甲方法人");
        text.setAddressA("甲方地址");
        text.setPartyB("乙方企业");
        text.setLegalPersonB("乙方法人");
        text.setAddressB("乙方地址");
        text.setAddress("东洼水田，西洼水田");
        text.setArea("120.33");
        text.setUnitPrice("20");
        text.setTotalPrice("2500");
        text.setStartYear("2023");
        text.setStartMonth("12");
        text.setStartDay("10");
        text.setEndYear("2023");
        text.setEndMonth("12");
        text.setEndDay("11");
        text.setSupplement("补充条款");
        return text;
    }

    public static <T> String Pdf(String templateUrl,T t){
        try {

            String htmlStr = text(htmlText(templateUrl), t);
            InputStream inputStream = new ByteArrayInputStream(htmlStr.getBytes());
            String tempDir = System.getProperty("java.io.tmpdir");
            //标识字段
            Field field = t.getClass().getDeclaredField("code");
            field.setAccessible(true);
            String code = (String) field.get(t);
            //输出pdf
            File outFile = new File(tempDir + code + ".pdf");
            System.out.println(tempDir + code + ".pdf");
            PdfWriter pdfWriter = new PdfWriter(outFile);
            PdfDocument pdfDocument = new PdfDocument(pdfWriter);
            Document doc = new Document(pdfDocument);
            pdfDocument.setDefaultPageSize(PageSize.A4);
            ConverterProperties pro = new ConverterProperties();
            FontProvider fontProvider = new DefaultFontProvider();
            fontProvider.addFont("simfang.ttf");
            pro.setFontProvider(fontProvider);
            pro.setCharset(StandardCharsets.UTF_8.name());
            //页码
            pdfDocument.addEventHandler(PdfDocumentEvent.END_PAGE, event -> {
                PdfDocumentEvent pdfEvent = (PdfDocumentEvent) event;
                int pageNumber = pdfEvent.getDocument().getPageNumber(pdfEvent.getPage());
                PdfCanvas canvas = new PdfCanvas(pdfEvent.getPage());
                Rectangle pageSize = pdfEvent.getPage().getPageSize();
                float y = pageSize.getBottom() + 20;
                // 在页面底部右侧位置添加页码
                canvas.beginText()
                        .setFontAndSize(pdfEvent.getDocument().getDefaultFont(), 12)
                        .moveText((pageSize.getRight() - doc.getRightMargin() + (pageSize.getLeft() + doc.getLeftMargin())) / 2,y)
                        .showText(pageNumber+"")
                        .endText();
            });
            HtmlConverter.convertToPdf(inputStream, pdfDocument,pro);
            pdfWriter.close();
            pdfDocument.close();
            inputStream.close();
            return tempDir + code + ".pdf";
        } catch (IOException | IllegalAccessException | NoSuchFieldException e) {
            e.printStackTrace();
        }
        return "";
    }

    private static String htmlText(String templateUrl){
        if(StringUtil.isBlank(templateUrl)){
            throw new RuntimeException("templateUrl is null");
        }
        try {
            //获取项目resource文件夹下面文件
            File file = new File(ClassLoader.getSystemResource(templateUrl).toURI()); // 替换成你的HTML文件路径
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), Charset.forName("GBK")));

            String line;
            StringBuilder htmlContent = new StringBuilder();
            while ((line = br.readLine()) != null) {
                htmlContent.append(line);
            }
            br.close();
            System.out.println(htmlContent.toString());
            return htmlContent.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }


    private static<T> String text(String str, T data) throws IllegalAccessException {
        Pattern pattern = Pattern.compile("\\$\\{([^}]*)\\}");
        Matcher matcher = pattern.matcher(str);
        // 执行替换
        StringBuffer result = new StringBuffer();
        while (matcher.find()) {
            String parameterName = matcher.group(1); // 获取参数名
            String replacement = getReplacement(parameterName,data); // 根据参数名获取实际替换的值
            replacement  = Optional.ofNullable(replacement).orElse("");
            // 将匹配的"${param}"替换为实际值
            matcher.appendReplacement(result, Matcher.quoteReplacement(replacement));
        }
        matcher.appendTail(result);
        return result.toString();
    }


    private static <T> String getReplacement(String parameterName,T t) throws IllegalAccessException {
        Field[] fields = t.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.getName().equals(parameterName)) {
                field.setAccessible(true);
                return (String) field.get(t);
            }
        }
        return "";
    }
}
